package common.fengkai.filepost.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;

public class Base64util {
    /**
     * 将文件转成base64 字符串
     *
     * @param
     * @return *
     * @throws Exception
     */
    public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        long size = inputFile.getChannel().size();
        System.out.println("size==="+size);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return new BASE64Encoder().encode(buffer);
    }
    /**
     * 将base64字符解码保存文件
     *
     * @param base64Code
     * @param targetPath 输出完整路径文件夹路径  catalogue 输出完整路径 包括文件名
     * @throws Exception
     */
    public static void decoderBase64File(String base64Code, String targetPath,String catalogue)
            throws Exception {
        File file = new File(catalogue);
        if(file.exists()==false){
            file.mkdirs();
        }
        byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();
    }
    public static byte[] decoderBase64ToByte(String base64Code) throws IOException {
       return  new BASE64Decoder().decodeBuffer(base64Code);
    }


    /**
     * 将文件转化为byte[]数组
     * @return
     * @throws IOException
     */
    public static  byte[] decoderFileTobytes(String path) throws IOException {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        long size = inputFile.getChannel().size();
        System.out.println("size==="+size);
        byte[] buffer = new byte[(int) file.length()];
        return buffer;
    }


    /**
     * 将数组转化为base64字符串
     * @return
     * @throws IOException
     */
    public static  String decoderBytesFileToBase64(byte[] bytes) throws IOException {
        String encode = new BASE64Encoder().encode(bytes);
        return encode;
    }

    /**
     * 将byte[]转化为File
     * @return
     * @throws IOException
     */




//       public static void main(String[] args) throws Exception {
//           byte[] bytes = base64tuil.decoderBase64FileTobytes("C:\\Users\\carry\\Desktop\\项目资料\\非车简易测试文件\\0606.pdf");
//           System.out.println(bytes.toString());
//
//
//       }
}
